package com.byx.chatserver.service.impl;

import com.byx.chatserver.entity.Friend;
import com.byx.chatserver.entity.ResultCode;
import com.byx.chatserver.entity.SimpleFriend;
import com.byx.chatserver.mapper.IFriendMapper;
import com.byx.chatserver.mapper.IUserMapper;
import com.byx.chatserver.service.IFriendService;
import com.byx.chatserver.vo.FriendParam;
import com.byx.springboot.unifiedresponseresult.entity.ServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * FriendServiceImpl
 *
 * @author Superb
 * @date 2021/4/30 22:09
 */
@Slf4j
@Service
public class FriendServiceImpl implements IFriendService {
    @Resource
    private IFriendMapper friendMapper;
    @Resource
    private IUserMapper userMapper;

    @Override
    public void addFriend(FriendParam friendParam) {
        Long userId = friendParam.getUserId() == null ? userMapper.getUserIdByLoginId(friendParam.getUserLoginId()) : friendParam.getUserId();
        Long friendId = friendParam.getFriendId() == null ? userMapper.getUserIdByLoginId(friendParam.getFriendLoginId()) : friendParam.getFriendId();
        //向自己的数据库添加对方信息
        friendParam.setUserId(userId);
        friendParam.setFriendId(friendId);
        friendMapper.insertFriendByParam(friendParam);
        //向对方添加自己信息
        friendParam.setUserId(friendId);
        friendParam.setFriendId(userId);
        friendParam.setRemark(userMapper.getUserNickNameById(userId));
        friendParam.setFriendGroupId(friendMapper.queryUserDefaultGroupId(friendId));
        friendMapper.insertFriendByParam(friendParam);
    }

    @Override
    public void deleteFriend(Long userId, Long friendId) {
        friendMapper.deleteFriendById(userId,friendId);
    }

    @Override
    public void modifyFriend(FriendParam friendParam) {

    }

    @Override
    public List<SimpleFriend> getAllFriends(Long loginId) {
        List<SimpleFriend> friends;
        try {
            friends=friendMapper.getAllFriends(loginId);
        }catch (Exception e){
            e.printStackTrace();
            log.error("getAllFriends",e);
            throw new ServerException(ResultCode.INTERNAL_SERVER_ERROR);
        }
        return friends;
    }

    @Override
    public Friend getFriendDetailInfo(Long loginId, Long friendLoginId) {
        try {
            return friendMapper.getFriend(loginId,friendLoginId);
        }catch (Exception e){
            log.error("getFriendDetailInfo",e);
            throw new ServerException(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public void changeFriendRemark(Long userId, Long friendId, String remark) {
        friendMapper.changeFriendRemarkName(userId,friendId,remark);
    }

    @Override
    public Friend getFriendDetailInfoByLoginId(Long userId, String friendId) {
        return friendMapper.getFriendByLoginId(userId,friendId);
    }
}
